package com.tanhua.dubbo.server.api;


import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 今日佳人
     * 获取最高得分数据信息
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {


        //构建查询条件
        //根据用户id获取mongodb中包含用户id的信息的佳人信息
        Criteria criteria = Criteria.where("toUserId").is(userId);
        //再根据佳人的score排序
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(1);


        //执行查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        //然后返回佳人伪数据
        return recommendUser;
    }

    /**
     * 推荐用户列表
     * 按照最高得分排序
     *
     * @param userId   用户id
     * @param pageNum  分页码
     * @param pageSize 每页条目数
     * @return
     */
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {

        //构建分页查询的参数
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Order.desc("score")));

        //构建mongodb查询条件
        Criteria criteria = Criteria.where("toUserId").is(userId);
        Query query = Query.query(criteria).with(pageRequest);

        //查询
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);

        return new PageInfo<>(0, pageNum, pageSize, recommendUserList);
    }


    /**
     * 查询好友的缘分值
     *
     * @param userId   佳人id
     * @param toUserId 当前用户id
     * @return
     */
    @Override
    public double queryScore(Long userId, Long toUserId) {

        Query query = Query.query(Criteria.where("toUserId").is(toUserId)
                .and("userId").is(userId));

        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            return 0;
        }
        return recommendUser.getScore();
    }
}
